import { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Card, Upload, Select, Modal, Image, message } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import './index.css'
import useJwt from '../../UseJwt';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (file: FileType): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const AvatarToCartoon = () => {

  // 文件列表
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modelSrc, setModelSrc] = useState('')
  const [modelType, setModelType ] = useState('01')

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }

    // setPreviewImage(file.url || (file.preview as string));
    // setPreviewOpen(true);
  };

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>
    setFileList(newFileList);

  const handleCustomRequest = () => {
    console.log('customRequest')
    return true
  }

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </button>
  );

  // 点击转换按钮
  const handleTransfrom = async () => {
    if (!fileList.length) {
      return
    }

    const file = fileList[0]
    const fd = new FormData()
    fd.append('name', file.name)
    fd.append('modelType', modelType)
    fd.append('file', (file.originFileObj as Blob), 'file')

    message.warning('正在处理，请稍候...')
    const res = await useJwt.imgToCartton(fd)
    console.log('data', res)
    if (res.code !== 200) {
      return
    }

    setModelSrc(res.data)
    showModal()
  }

  // 改变模型类型
  const handleChangeModelType = (modelType: string) => {
    setModelType(modelType)
  }


  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <div
      className="h-[91vh] rounded p-[1rem] flex flex-col "
    >
      <div className="cartoon flex-1 flex ">
        <Card
          title="图片转卡通"
          extra={
            <Select
              defaultValue="01"
              style={{ width: 300 }}
              onChange={handleChangeModelType}
              options={[
                { value: '01', label: 'CSRNet图像调色' },
                { value: '02', label: '人像卡通模型' },
                { value: '03', label: 'DDColor图像上色' },
                { value: '04', label: 'GPEN 人像修复增强' },
                { value: '05', label: 'DCT-Net人像卡通化-艺术' },
                { value: '06', label: 'DCT-Net人像卡通化模型-原神风' },
                { value: '07', label: '人像卡通化-扩散模型-插画' },
                { value: '08', label: 'DCT-Net人像卡通化-扩散模型-漫画' },
                { value: '09', label: 'DCT-Net人像卡通化-素描' },
              ]}
            />
          }
          style={{ flex: 1 }}
        >
          <div
            className='h-[680px] flex justify-center items-center'
          >

            <Upload
              action=""
              listType="picture-card"
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handleChange}
              customRequest={handleCustomRequest}
              beforeUpload={() => false}
            >
              {fileList.length >= 1 ? null : uploadButton}
            </Upload>
          </div>
        </Card>

      </div>

      <footer className='flex flex-row-reverse mt-2 mb-2'>
        <Button
          type="primary"
          className='ml-2'
          onClick={handleTransfrom}
        >
          转换
        </Button>
        <Button
          onClick={ () => { setFileList([]) } }
        >
          重置
        </Button>
      </footer>

      {/* 弹框 */}

      <Modal
        title="图片"
        centered
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        width={500}
        cancelText="取消"
        okText="确定"
      >
        
        <Image
          width={400}
          height={300}
          src={modelSrc}
          preview={false}
        />
      </Modal>
    </div>
  )
}


export default AvatarToCartoon